package com.skyon.sdk;

import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by chen on 2018/6/10.
 */

public class HookWebViewClient extends WebViewClient {
    private String checkId = "";
    private boolean isFirst = true;

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        String lgnUr = "";
        CookieManager cookieManager = CookieManager.getInstance();
        String cookieStr = cookieManager.getCookie(url);
        if (cookieStr != null && !cookieStr.equals("")) {
            String[] split = cookieStr.split(";");
            try {
                if (split.length > 0) {
                    for (String s : split) {
                        if (s.contains("check_id")) {
                            checkId = s.split("=")[1];
                        } else {
                            if (isFirst) {
                                checkId = createCheckId();
                            }
                        }
                        if (s.contains("sky_lgn_ur")) {
                            lgnUr = s.split("=")[1];
                        }
                    }
                    isFirst = false;
                }
            } catch (Exception e) {
            }
            SkyonSdk.h5LoadEvent(url, System.currentTimeMillis(), checkId, lgnUr, view.getTitle());
        }
    }

    private String createCheckId() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 16; i++) {
            String n = Integer.toHexString((int) Math.floor(Math.random() * 16.0));
            sb.append(n);
        }
        return sb.toString();
    }
}
